<?php

namespace app\api\logic;

use app\common\enum\RefundEnum;

use app\common\logic\BaseLogic;
use app\common\model\pay\PayConfig;

use app\common\model\refund\RefundRecord;
use app\common\model\user\UserGroup;
use think\facade\Db;

class RefundLogic extends BaseLogic
{
    public static function create($params)
    {
        Db::startTrans();
        try {

            $payConfig = PayConfig::find(['pay_way'=> $params['pay_way']]);
            if (empty($payConfig)) {
                throw new \Exception('打款方式不存在');
            }

            $userGroup = UserGroup::find(['id'=> $params['group_id']]);
            if (empty($userGroup)) {
                throw new \Exception('客户不存在');
            }
            if($params['order_amount']>$userGroup->user_money){
                throw new \Exception('客户余额不足,退款金额不能超过'.$userGroup->user_money);
            }

            $service_fee = $payConfig['service_fee'];
            $refund_amount =  $params['order_amount']*(1 - $service_fee);

            // 生成退款记录
            $recordSn = generate_sn(RefundRecord::class, 'sn');
            $record = RefundRecord::create([
                'sn' => $recordSn,
                'user_id' => $params['user_id'],
                'group_id' => $params['group_id'],
                'order_type' => RefundEnum::ORDER_TYPE_RECHARGE,
                'service_fee'=>$service_fee,
                'order_amount' => $params['order_amount'],//订单金额
                'refund_amount' => $refund_amount,//退款金额
                'refund_type' => RefundEnum::TYPE_ADMIN,
                'transaction_id' => $params['transaction_id'] ?? '',
                'refund_way' => RefundEnum::getRefundWayByPayWay($params['pay_way']),
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function lists(array $params): array
    {
        $where['group_id'] = $params['group_id'];
        // 分页
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 15;

        // 统计数据
        $count = RefundRecord::where($where)->count();

        // 获取数据
        $list = RefundRecord::where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();

        return [
            'count' => $count,
            'list' => $list,
            'page' => $page,
            'limit' => $limit
        ];
    }

}